package com.ssca.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.ssca.mybatis.AliasesDAO;

public class ReadDataFromFile {

	public static void main(String[] args) {
		// System.out.println(
		// parseLine("Lcom/1/1;-> Lcom/2/2;")[0] + " " + parseLine("Lcom/1/1;->
		// Lcom/2/2;")[1]);
		File txtRoot = new File("/Users/yujianbo/Desktop/relationTXT/");
		for (File f : txtRoot.listFiles()) {
			try {
				readFileToDB(f.getAbsolutePath());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("unused")
	public static void readFileToDB(String filePath) throws Exception {

		File dataFile = new File(filePath);
		FileInputStream fis = new FileInputStream(dataFile);
		InputStreamReader isr = new InputStreamReader(fis);
		BufferedReader br = new BufferedReader(isr);
		String line = "";
		while ((line = br.readLine()) != null) {
			System.out.println(line);
			String result[] = parseLine(line);
			// result[0]和result[1]分别是source和des
			Reader reader;
			try {
				reader = Resources.getResourceAsReader("MybatisConfig.xml");
				SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
				SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader);
				SqlSession sqlSession = sqlSessionFactory.openSession();
				AliasesDAO aliasesDAO = sqlSession.getMapper(AliasesDAO.class);
				// int sourceId = aliasesDAO.findSource(result[0]);
				// int desId = aliasesDAO.findDes(result[1]);
				// System.out.println("source:"+sourceId+" des:"+desId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// close
		br.close();
		isr.close();
		fis.close();
	}

	private static String[] parseLine(String s) {
		String source = s.split("->")[0].trim();
		String des = s.split("->")[1].trim();
		source = convert(source);
		des = convert(des);
		String[] re = new String[2];
		re[0] = source;
		re[1] = des;
		return re;
	}

	private static String convert(String s) {
		String re = s.substring(1, s.length() - 1);
		re = re.replaceAll("/", ".");
		return re;
	}

}
